use crate::field::{VddField, VddFieldType};
use crate::i18n_text::E_ARG_BAD;
use crate::{i18n, Ares, Astr, JsonSupportTrait, RecordId, UserId, DT_FORMAT, D_FORMAT, T_FORMAT};
use base64ct::{Base64, Encoding};
use chrono::{NaiveDate, NaiveDateTime, NaiveTime};
use rsa::rand_core::OsRng;
use rsa::{Pkcs1v15Encrypt, RsaPublicKey};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::cmp::Ordering;
use std::str::FromStr;
use std::sync::Arc;

#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(tag = "T", content = "C")]
pub enum VddValue {
    NULL,
    EncryptedB64(String), // 加密后的base64字符串，用来替换需要加密传输的值
    S101(String),
    S102(String),
    S103(String),
    S201(i64),
    S202(f64),
    S211(bool),
    S212(i64),
    S291(u64),
    S301(NaiveDate),
    S302(NaiveTime),
    S303(NaiveDateTime),
    S401 { v: u64, d: String },
    S801(String),
    S901(RecordId),
    S911(UserId),
    S903(RecordId),
    S501,
    M101(Vec<String>),
    M201(Vec<i64>),
    M202(Vec<f64>),
    M301(Vec<NaiveDate>),
    M302(Vec<NaiveTime>),
    M303(Vec<NaiveDateTime>),
    M401 { v: Vec<u64>, d: Vec<String> },
    M801(Vec<String>),
    M901(Vec<RecordId>),
    M911(Vec<UserId>),
    M903(Vec<RecordId>),
}

impl VddValue {
    pub fn from_json(field: &VddField, j: &Value, operator: &UserId) -> Self {
        match field.field_type.as_ref() {
            VddFieldType::FtString { .. } => {
                if field.multi {
                    if j.is_array() {
                        let v = j
                            .as_array()
                            .unwrap()
                            .iter()
                            .map(|item| {
                                if item.is_string() {
                                    item.as_str().unwrap().to_string()
                                } else {
                                    item.to_string()
                                }
                            })
                            .collect::<Vec<String>>();
                        VddValue::M101(v)
                    } else {
                        VddValue::NULL
                    }
                } else {
                    if let Some(x) = j.as_str() {
                        VddValue::S101(x.to_string())
                    } else {
                        VddValue::NULL
                    }
                }
            }
            VddFieldType::FtInt { .. } => {
                if field.multi {
                    if j.is_array() {
                        let v = j
                            .as_array()
                            .unwrap()
                            .iter()
                            .map(|item| item.try_hard_to_i64())
                            .filter(|item| item.is_some())
                            .map(|item| item.unwrap())
                            .collect::<Vec<i64>>();
                        VddValue::M201(v)
                    } else {
                        VddValue::NULL
                    }
                } else {
                    if let Some(v) = j.try_hard_to_i64() {
                        VddValue::S201(v)
                    } else {
                        VddValue::NULL
                    }
                }
            }
            VddFieldType::FtFloat { .. } => {
                if field.multi {
                    if j.is_array() {
                        let v = j
                            .as_array()
                            .unwrap()
                            .iter()
                            .map(|item| item.try_hard_to_f64())
                            .filter(|item| item.is_some())
                            .map(|item| item.unwrap())
                            .collect::<Vec<f64>>();
                        VddValue::M202(v)
                    } else {
                        VddValue::NULL
                    }
                } else {
                    if let Some(v) = j.try_hard_to_f64() {
                        VddValue::S202(v)
                    } else {
                        VddValue::NULL
                    }
                }
            }
            VddFieldType::FtBool => {
                if let Some(x) = j.as_bool() {
                    VddValue::S211(x)
                } else {
                    VddValue::S211(false)
                }
            }
            VddFieldType::FtDate(..) => {
                if field.multi {
                    if j.is_array() {
                        let v = j
                            .as_array()
                            .unwrap()
                            .iter()
                            .map(|item| NaiveDate::parse_from_str(item.as_str().unwrap(), D_FORMAT))
                            .filter(|item| item.is_ok())
                            .map(|item| item.unwrap())
                            .collect::<Vec<NaiveDate>>();
                        VddValue::M301(v)
                    } else {
                        VddValue::NULL
                    }
                } else {
                    j.as_str()
                        .map(|x| VddValue::S301(NaiveDate::parse_from_str(x, D_FORMAT).unwrap()))
                        .unwrap_or(VddValue::NULL)
                }
            }
            VddFieldType::FtTime(..) => {
                if field.multi {
                    if j.is_array() {
                        let v = j
                            .as_array()
                            .unwrap()
                            .iter()
                            .map(|x| NaiveTime::parse_from_str(x.as_str().unwrap(), T_FORMAT))
                            .filter(|x| x.is_ok())
                            .map(|x| x.unwrap())
                            .collect::<Vec<NaiveTime>>();
                        VddValue::M302(v)
                    } else {
                        VddValue::NULL
                    }
                } else {
                    j.as_str()
                        .map(|x| VddValue::S302(NaiveTime::parse_from_str(x, T_FORMAT).unwrap()))
                        .unwrap_or(VddValue::NULL)
                }
            }
            VddFieldType::FtDateTime(..) => {
                if field.multi {
                    if j.is_array() {
                        let v = j
                            .as_array()
                            .unwrap()
                            .iter()
                            .map(|x| NaiveDateTime::parse_from_str(x.as_str().unwrap(), DT_FORMAT))
                            .filter(|x| x.is_ok())
                            .map(|x| x.unwrap())
                            .collect::<Vec<NaiveDateTime>>();
                        VddValue::M303(v)
                    } else {
                        panic!("{}", i18n!(E_ARG_BAD))
                    }
                } else {
                    j.as_str()
                        .map(|x| {
                            VddValue::S303(NaiveDateTime::parse_from_str(x, DT_FORMAT).unwrap())
                        })
                        .unwrap_or(VddValue::NULL)
                }
            }
            VddFieldType::FtFile(..) => {
                if j["v"].as_u64().is_some() && j["d"].as_str().is_some() {
                    VddValue::S401 {
                        v: j["v"].as_u64().unwrap(),
                        d: j["d"].as_str().unwrap().to_string(),
                    }
                } else {
                    VddValue::NULL
                }
            }
            VddFieldType::FtComputed(..) => VddValue::S501,
            VddFieldType::FtCode(..) => {
                if field.multi {
                    if j.is_array() {
                        let v = j
                            .as_array()
                            .unwrap()
                            .iter()
                            .map(|x| x.as_str())
                            .filter(|x| x.is_some())
                            .map(|x| x.unwrap().to_string())
                            .collect::<Vec<String>>();
                        VddValue::M801(v)
                    } else {
                        VddValue::NULL
                    }
                } else {
                    if let Some(x) = j.as_str() {
                        VddValue::S801(x.to_string())
                    } else {
                        VddValue::NULL
                    }
                }
            }
            VddFieldType::FtModel { .. } => {
                if field.multi {
                    if j.is_array() {
                        let v = j
                            .as_array()
                            .unwrap()
                            .iter()
                            .map(|x| x.as_u64())
                            .filter(|x| x.is_some())
                            .map(|x| RecordId(x.unwrap()))
                            .collect::<Vec<RecordId>>();
                        VddValue::M901(v)
                    } else {
                        VddValue::NULL
                    }
                } else {
                    j.as_u64()
                        .map(|x| VddValue::S901(RecordId(x)))
                        .unwrap_or(VddValue::NULL)
                }
            }
            VddFieldType::FtAutoIncreaseInt { start, .. } => {
                VddValue::S212(j.try_hard_to_i64().unwrap_or(*start))
            } // 自动计算的值类型需要数据库支持，放在后面填充
            VddFieldType::FtAutoIncreaseIntGlobal => VddValue::S291(0u64),
            VddFieldType::FtUserId => j
                .as_u64()
                .map(|x| VddValue::S911(UserId(x)))
                .unwrap_or(VddValue::NULL),
            VddFieldType::FtUserSelf => VddValue::S911(operator.clone()),
            VddFieldType::FtJson { .. } => j
                .as_str()
                .map(|x| VddValue::S102(x.to_string()))
                .unwrap_or(VddValue::NULL),
            VddFieldType::FtYaml { .. } => j
                .as_str()
                .map(|x| VddValue::S103(x.to_string()))
                .unwrap_or(VddValue::NULL),
            VddFieldType::FtModelSelf(..) => {
                if field.multi {
                    if j.is_array() {
                        let v = j
                            .as_array()
                            .unwrap()
                            .iter()
                            .map(|x| x.as_u64())
                            .filter(|x| x.is_some())
                            .map(|x| RecordId(x.unwrap()))
                            .collect::<Vec<RecordId>>();
                        VddValue::M903(v)
                    } else {
                        VddValue::NULL
                    }
                } else {
                    j.as_u64()
                        .map(|x| VddValue::S903(RecordId(x)))
                        .unwrap_or(VddValue::NULL)
                }
            }
        }
    }

    pub fn get_simple_display(&self) -> Astr {
        match self {
            VddValue::NULL => "<NULL>".into(),
            VddValue::S101(v)
            | VddValue::S102(v)
            | VddValue::S103(v)
            | VddValue::EncryptedB64(v) => Arc::from(v.to_owned()),
            VddValue::S201(v) => v.to_string().into(),
            VddValue::S202(v) => Arc::from(v.to_string()),
            VddValue::S211(v) => Arc::from(v.to_string()),
            VddValue::S212(v) => v.to_string().into(),
            VddValue::S291(v) => v.to_string().into(),
            VddValue::S301(v) => Arc::from(v.format(D_FORMAT).to_string()),
            VddValue::S302(v) => Arc::from(v.format(T_FORMAT).to_string()),
            VddValue::S303(v) => Arc::from(v.format(DT_FORMAT).to_string()),
            VddValue::S401 { v: _, d } => Arc::from(d.to_owned()),
            VddValue::M101(v) => Arc::from(json!(v).to_string()),
            VddValue::M201(v) => Arc::from(json!(v).to_string()),
            VddValue::M202(v) => Arc::from(json!(v).to_string()),
            VddValue::M301(v) => Arc::from(json!(v).to_string()),
            VddValue::M302(v) => Arc::from(json!(v).to_string()),
            VddValue::M303(v) => Arc::from(json!(v).to_string()),
            VddValue::S801(_) => "".into(),
            VddValue::S901(_) => "".into(),
            VddValue::S911(_) => "".into(),
            VddValue::S903(_) => "".into(),
            VddValue::S501 => "".into(),
            VddValue::M401 { .. } => "".into(),
            VddValue::M801(_) => "".into(),
            VddValue::M901(_) => "".into(),
            VddValue::M911(_) => "".into(),
            VddValue::M903(_) => "".into(),
        }
    }

    pub fn compare(
        field_type: &VddFieldType,
        j_a: &VddValue,
        j_b: &VddValue,
    ) -> Result<Ordering, Astr> {
        match field_type {
            VddFieldType::FtInt { .. } => {
                let v_a: i64 = j_a.try_into().expect(i18n!(E_ARG_BAD).as_ref());
                let v_b: i64 = j_b.try_into().expect(i18n!(E_ARG_BAD).as_ref());
                Ok(v_a.cmp(&v_b))
            }
            VddFieldType::FtFloat { .. } => {
                let v_a = TryInto::<f64>::try_into(j_a).expect(i18n!(E_ARG_BAD).as_ref());
                let v_b = TryInto::<f64>::try_into(j_b).expect(i18n!(E_ARG_BAD).as_ref());
                Ok(v_a.partial_cmp(&v_b).unwrap())
            }
            VddFieldType::FtDate(..) => {
                let v_a = TryInto::<NaiveDate>::try_into(j_a).expect(i18n!(E_ARG_BAD).as_ref());
                let v_b = TryInto::<NaiveDate>::try_into(j_b).expect(i18n!(E_ARG_BAD).as_ref());
                Ok(v_a.cmp(&v_b))
            }
            VddFieldType::FtTime(..) => {
                let v_a = TryInto::<NaiveTime>::try_into(j_a).expect(i18n!(E_ARG_BAD).as_ref());
                let v_b = TryInto::<NaiveTime>::try_into(j_b).expect(i18n!(E_ARG_BAD).as_ref());
                Ok(v_a.cmp(&v_b))
            }
            VddFieldType::FtDateTime(..) => {
                let v_a = TryInto::<NaiveDateTime>::try_into(j_a).expect(i18n!(E_ARG_BAD).as_ref());
                let v_b = TryInto::<NaiveDateTime>::try_into(j_b).expect(i18n!(E_ARG_BAD).as_ref());
                Ok(v_a.cmp(&v_b))
            }
            _ => Err(i18n!(1206)),
        }
    }

    /// 支持参数传null
    pub fn is_between(&self, r0: Astr, r1: Astr) -> Result<bool, Astr> {
        match self {
            VddValue::S201(v) | VddValue::S212(v) => {
                let v0 = i64::from_str(&r0);
                let v1 = i64::from_str(&r1);
                Ok(match (v0, v1) {
                    (Ok(a_val), Ok(b_val)) => *v >= a_val && *v <= b_val,
                    (Ok(a_val), Err(_)) => *v >= a_val,
                    (Err(_), Ok(b_val)) => *v <= b_val,
                    (Err(_), Err(_)) => true,
                })
            }
            VddValue::S202(v) => {
                let v0 = f64::from_str(&r0);
                let v1 = f64::from_str(&r1);
                Ok(match (v0, v1) {
                    (Ok(a_val), Ok(b_val)) => *v >= a_val && *v <= b_val,
                    (Ok(a_val), Err(_)) => *v >= a_val,
                    (Err(_), Ok(b_val)) => *v <= b_val,
                    (Err(_), Err(_)) => true,
                })
            }
            VddValue::S301(v) => {
                let v0 = NaiveDate::parse_from_str(&r0, D_FORMAT);
                let v1 = NaiveDate::parse_from_str(&r1, D_FORMAT);
                Ok(match (v0, v1) {
                    (Ok(a_val), Ok(b_val)) => v.ge(&a_val) && v.le(&b_val),
                    (Ok(a_val), Err(_)) => v.ge(&a_val),
                    (Err(_), Ok(b_val)) => v.le(&b_val),
                    (Err(_), Err(_)) => true,
                })
            }
            VddValue::S302(v) => {
                let v0 = NaiveTime::parse_from_str(&r0, D_FORMAT);
                let v1 = NaiveTime::parse_from_str(&r1, D_FORMAT);
                Ok(match (v0, v1) {
                    (Ok(a_val), Ok(b_val)) => v.ge(&a_val) && v.le(&b_val),
                    (Ok(a_val), Err(_)) => v.ge(&a_val),
                    (Err(_), Ok(b_val)) => v.le(&b_val),
                    (Err(_), Err(_)) => true,
                })
            }
            VddValue::S303(v) => {
                let v0 = NaiveDateTime::parse_from_str(&r0, D_FORMAT);
                let v1 = NaiveDateTime::parse_from_str(&r1, D_FORMAT);
                Ok(match (v0, v1) {
                    (Ok(a_val), Ok(b_val)) => v.ge(&a_val) && v.le(&b_val),
                    (Ok(a_val), Err(_)) => v.ge(&a_val),
                    (Err(_), Ok(b_val)) => v.le(&b_val),
                    (Err(_), Err(_)) => true,
                })
            }
            _ => Err("无法参与计算的字段类型".into()),
        }
    }

    pub fn is_in(&self, values: &[Astr]) -> Result<bool, Astr> {
        match self {
            VddValue::S201(v) | VddValue::S212(v) => {
                let vs = values
                    .iter()
                    .map(|x| i64::from_str(x))
                    .filter(|x| x.is_ok())
                    .map(|x| x.unwrap())
                    .collect::<Vec<i64>>();
                Ok(vs.contains(v))
            }
            VddValue::S202(v) => {
                let vs = values
                    .iter()
                    .map(|x| f64::from_str(x))
                    .filter(|x| x.is_ok())
                    .map(|x| x.unwrap())
                    .collect::<Vec<f64>>();
                Ok(vs.contains(v))
            }
            VddValue::S301(v) => {
                let vs = values
                    .iter()
                    .map(|x| NaiveDate::parse_from_str(x, D_FORMAT))
                    .filter(|x| x.is_ok())
                    .map(|x| x.unwrap())
                    .collect::<Vec<NaiveDate>>();
                Ok(vs.contains(v))
            }
            VddValue::S302(v) => {
                let vs = values
                    .iter()
                    .map(|x| NaiveTime::parse_from_str(x, T_FORMAT))
                    .filter(|x| x.is_ok())
                    .map(|x| x.unwrap())
                    .collect::<Vec<NaiveTime>>();
                Ok(vs.contains(v))
            }
            VddValue::S303(v) => {
                let vs = values
                    .iter()
                    .map(|x| NaiveDateTime::parse_from_str(x, DT_FORMAT))
                    .filter(|x| x.is_ok())
                    .map(|x| x.unwrap())
                    .collect::<Vec<NaiveDateTime>>();
                Ok(vs.contains(v))
            }
            _ => Err("无法参与计算的字段类型".into()),
        }
    }

    /// 向多值字段添加添加一个元素
    pub fn add_item(&mut self, item: &str) -> Ares {
        match self {
            VddValue::M101(v) | VddValue::M801(v) => {
                v.push(item.to_string());
                Ok(())
            }
            VddValue::M201(v) => {
                v.push(i64::from_str(item).unwrap());
                Ok(())
            }
            VddValue::M202(v) => {
                v.push(f64::from_str(item).unwrap());
                Ok(())
            }
            VddValue::M301(v) => {
                v.push(NaiveDate::parse_from_str(item, D_FORMAT).unwrap());
                Ok(())
            }
            VddValue::M302(v) => {
                v.push(NaiveTime::parse_from_str(item, T_FORMAT).unwrap());
                Ok(())
            }
            VddValue::M303(v) => {
                v.push(NaiveDateTime::parse_from_str(item, DT_FORMAT).unwrap());
                Ok(())
            }
            VddValue::M901(v) => {
                v.push(RecordId(u64::from_str(item).unwrap()));
                Ok(())
            }
            _ => Err("字段类型不支持此操作".into()),
        }
    }

    /// 从多值字段删除一个元素
    pub fn remove_item(&mut self, item: &str) -> Ares {
        match self {
            VddValue::M101(v) | VddValue::M801(v) => {
                v.retain(|x| x != item);
                Ok(())
            }
            VddValue::M201(v) => {
                let item = i64::from_str(item).unwrap();
                v.retain(|x| x != &item);
                Ok(())
            }
            VddValue::M202(v) => {
                let item = f64::from_str(item).unwrap();
                v.retain(|x| x != &item);
                Ok(())
            }
            VddValue::M301(v) => {
                let item = NaiveDate::parse_from_str(item, D_FORMAT).unwrap();
                v.retain(|x| x != &item);
                Ok(())
            }
            VddValue::M302(v) => {
                let item = NaiveTime::parse_from_str(item, T_FORMAT).unwrap();
                v.retain(|x| x != &item);
                Ok(())
            }
            VddValue::M303(v) => {
                let item = NaiveDateTime::parse_from_str(item, DT_FORMAT).unwrap();
                v.retain(|x| x != &item);
                Ok(())
            }
            VddValue::M901(v) => {
                v.push(RecordId(u64::from_str(item).unwrap()));
                Ok(())
            }
            _ => Err("字段类型不支持此操作".into()),
        }
    }

    /// 修改多值字段中的一个元素
    pub fn change_item(&mut self, idx: usize, item: &str) -> Ares {
        match self {
            VddValue::M101(v) | VddValue::M801(v) => {
                if idx > v.len() {
                    Err("下标越界".into())
                } else {
                    v.insert(idx, item.to_string());
                    Ok(())
                }
            }
            VddValue::M201(v) => {
                if idx > v.len() {
                    Err("下标越界".into())
                } else {
                    let item = i64::from_str(item).unwrap();
                    v.insert(idx, item);
                    Ok(())
                }
            }
            VddValue::M202(v) => {
                if idx > v.len() {
                    Err("下标越界".into())
                } else {
                    let item = f64::from_str(item).unwrap();
                    v.insert(idx, item);
                    Ok(())
                }
            }
            VddValue::M301(v) => {
                if idx > v.len() {
                    Err("下标越界".into())
                } else {
                    let item = NaiveDate::parse_from_str(item, D_FORMAT).unwrap();
                    v.insert(idx, item);
                    Ok(())
                }
            }
            VddValue::M302(v) => {
                if idx > v.len() {
                    Err("下标越界".into())
                } else {
                    let item = NaiveTime::parse_from_str(item, T_FORMAT).unwrap();
                    v.insert(idx, item);
                    Ok(())
                }
            }
            VddValue::M303(v) => {
                if idx > v.len() {
                    Err("下标越界".into())
                } else {
                    let item = NaiveDateTime::parse_from_str(item, DT_FORMAT).unwrap();
                    v.insert(idx, item);
                    Ok(())
                }
            }
            VddValue::M901(v) => {
                if idx > v.len() {
                    Err("下标越界".into())
                } else {
                    v.push(RecordId(u64::from_str(item).unwrap()));
                    Ok(())
                }
            }
            _ => Err("字段类型不支持此操作".into()),
        }
    }

    /// 字段类型改变时的检验与应用
    pub fn on_field_type_change(&self, to_type: VddFieldType) -> Result<Self, Astr> {
        let err_msg = "目标类型不受支持";
        let display = self.get_simple_display().to_string();
        match to_type {
            VddFieldType::FtString { .. } => Ok(VddValue::S101(display)),
            VddFieldType::FtJson { .. } => Ok(VddValue::S102(display)),
            VddFieldType::FtYaml { .. } => Ok(VddValue::S103(display)),
            VddFieldType::FtInt { .. } => match TryInto::<i64>::try_into(self) {
                Err(_) => Err(err_msg.into()),
                Ok(v) => Ok(VddValue::S201(v)),
            },
            VddFieldType::FtFloat { .. } => match TryInto::<f64>::try_into(self) {
                Err(_) => Err(err_msg.into()),
                Ok(v) => Ok(VddValue::S202(v)),
            },
            VddFieldType::FtBool => match TryInto::<bool>::try_into(self) {
                Err(_) => Err(err_msg.into()),
                Ok(v) => Ok(VddValue::S211(v)),
            },
            VddFieldType::FtDate(_) => {
                let v = NaiveDate::parse_from_str(display.as_str(), T_FORMAT);
                match v {
                    Ok(v) => Ok(VddValue::S301(v)),
                    Err(_) => Err(err_msg.into()),
                }
            }
            VddFieldType::FtTime(_) => {
                let v = NaiveTime::parse_from_str(display.as_str(), T_FORMAT);
                match v {
                    Ok(v) => Ok(VddValue::S302(v)),
                    Err(_) => Err(err_msg.into()),
                }
            }
            VddFieldType::FtDateTime(_) => {
                let v = NaiveDateTime::parse_from_str(display.as_str(), DT_FORMAT);
                match v {
                    Ok(v) => Ok(VddValue::S303(v)),
                    Err(_) => Err(err_msg.into()),
                }
            }
            _ => Err(err_msg.into()),
        }
    }
    /// 把字段值加密，使用当前用户的公钥
    pub fn encrypt_to_b64(&self, user_pub_key: &RsaPublicKey) -> String {
        match self {
            VddValue::EncryptedB64(v) => v.clone(),
            _ => {
                let msg = json!(self).to_string();
                let msg_e = user_pub_key
                    .encrypt(&mut OsRng, Pkcs1v15Encrypt::default(), msg.as_bytes())
                    .unwrap();
                Base64::encode_string(&msg_e)
            }
        }
    }

    /// 单值转成多重值
    pub fn s_to_m(&self) -> Option<Self> {
        match self {
            VddValue::S101(v) => {
                let new_v = serde_json::from_str::<Value>(v)
                    .map(|j| {
                        j.as_array()
                            .map(|j_items| {
                                j_items
                                    .iter()
                                    .map(|j_item| j_item.as_str())
                                    .filter(|j_item| j_item.is_some())
                                    .map(|j_item| j_item.unwrap().to_string())
                                    .collect::<Vec<String>>()
                            })
                            .unwrap_or(vec![v.to_string()])
                    })
                    .unwrap_or(vec![v.clone()]);
                Some(VddValue::M101(new_v))
            }
            VddValue::S201(v) => Some(VddValue::M201(vec![v.clone()])),
            VddValue::S202(v) => Some(VddValue::M202(vec![v.clone()])),
            VddValue::S301(v) => Some(VddValue::M301(vec![v.clone()])),
            VddValue::S302(v) => Some(VddValue::M302(vec![v.clone()])),
            VddValue::S303(v) => Some(VddValue::M303(vec![v.clone()])),
            VddValue::S401 { v, d } => Some(VddValue::M401 {
                v: vec![*v],
                d: vec![d.clone()],
            }),
            VddValue::S801(v) => Some(VddValue::M801(vec![v.clone()])),
            VddValue::S901(v) => Some(VddValue::M901(vec![v.clone()])),
            VddValue::S911(v) => Some(VddValue::M911(vec![v.clone()])),
            _ => None,
        }
    }

    ///
    pub fn m_to_s(&self) -> Option<Self> {
        match self {
            VddValue::M101(v) => Some(VddValue::S101(json!(v).to_string())),
            VddValue::M201(v) => v.first().map(|i| VddValue::S201(*i)),
            VddValue::M202(v) => v.first().map(|f| VddValue::S202(*f)),
            VddValue::M301(v) => v.first().map(|d| VddValue::S301(d.clone())),
            VddValue::M302(v) => v.first().map(|t| VddValue::S302(t.clone())),
            VddValue::M303(v) => v.first().map(|dt| VddValue::S303(dt.clone())),
            VddValue::M401 { v, d } => {
                let v1o = v.first();
                let d1o = d.first();
                match (v1o, d1o) {
                    (Some(v1), Some(d1)) => Some(VddValue::S401 {
                        v: v1.clone(),
                        d: d1.clone(),
                    }),
                    _ => None,
                }
            }
            VddValue::M801(v) => v.first().map(|code| VddValue::S801(code.clone())),
            VddValue::M901(v) => v.first().map(|rec_id| VddValue::S901(rec_id.clone())),
            VddValue::M911(v) => v.first().map(|user_id| VddValue::S911(user_id.clone())),
            _ => None,
        }
    }
}

impl Default for VddValue {
    fn default() -> Self {
        VddValue::NULL
    }
}

pub type VddValueRef = Arc<VddValue>;

#[derive(Debug, Clone)]
pub struct VddValueWithMeta {
    pub value: VddValueRef,
    pub rec_id: RecordId,
}

impl VddValueWithMeta {
    pub fn new_null(rec_id: RecordId) -> Self {
        VddValueWithMeta {
            rec_id,
            value: Arc::new(VddValue::default()),
        }
    }
}

impl TryFrom<&VddValue> for u64 {
    type Error = Astr;
    fn try_from(value: &VddValue) -> Result<Self, Self::Error> {
        match value {
            VddValue::S291(v) => Ok(*v),
            _ => Err("转换失败".into()),
        }
    }
}

impl TryFrom<&VddValue> for f64 {
    type Error = Astr;
    fn try_from(value: &VddValue) -> Result<Self, Self::Error> {
        match value {
            VddValue::S202(v) => Ok(*v),
            VddValue::S201(v) => Ok(*v as f64),
            _ => Err("转换失败".into()),
        }
    }
}

impl TryFrom<&VddValue> for bool {
    type Error = Astr;
    fn try_from(value: &VddValue) -> Result<Self, Self::Error> {
        match value {
            VddValue::S211(v) => Ok(*v),
            _ => Err("转换失败".into()),
        }
    }
}

impl TryFrom<&VddValue> for i64 {
    type Error = Astr;
    fn try_from(value: &VddValue) -> Result<Self, Self::Error> {
        match value {
            VddValue::S201(v) => Ok(*v),
            VddValue::S212(v) => Ok(*v),
            _ => Err("转换失败".into()),
        }
    }
}

impl TryFrom<&VddValue> for NaiveDate {
    type Error = Astr;
    fn try_from(value: &VddValue) -> Result<Self, Self::Error> {
        match value {
            VddValue::S301(v) => Ok(v.to_owned()),
            _ => Err("转换失败".into()),
        }
    }
}

impl TryFrom<&VddValue> for NaiveTime {
    type Error = Astr;
    fn try_from(value: &VddValue) -> Result<Self, Self::Error> {
        match value {
            VddValue::S302(v) => Ok(v.to_owned()),
            _ => Err("转换失败".into()),
        }
    }
}

impl TryFrom<&VddValue> for NaiveDateTime {
    type Error = Astr;
    fn try_from(value: &VddValue) -> Result<Self, Self::Error> {
        match value {
            VddValue::S303(v) => Ok(v.to_owned()),
            _ => Err("转换失败".into()),
        }
    }
}

impl TryFrom<&VddValue> for RecordId {
    type Error = Astr;
    fn try_from(value: &VddValue) -> Result<Self, Self::Error> {
        match value {
            VddValue::S901(v) => Ok(v.to_owned()),
            VddValue::S201(v) | VddValue::S212(v) => Ok(RecordId(*v as u64)),
            _ => Err("转换失败".into()),
        }
    }
}

impl TryFrom<&VddValue> for Astr {
    type Error = Astr;

    fn try_from(value: &VddValue) -> Result<Self, Self::Error> {
        match value {
            VddValue::S101(v) | VddValue::S102(v) | VddValue::S103(v) => Ok(v.to_owned().into()),
            VddValue::S201(v) => Ok(v.to_string().into()),
            VddValue::S202(v) => Ok(v.to_string().into()),
            VddValue::S211(v) => Ok(v.to_string().into()),
            VddValue::S212(v) => Ok(v.to_string().into()),
            VddValue::S291(v) => Ok(v.to_string().into()),
            VddValue::S301(v) => Ok(v.format(D_FORMAT).to_string().into()),
            VddValue::S302(v) => Ok(v.format(T_FORMAT).to_string().into()),
            VddValue::S303(v) => Ok(v.format(DT_FORMAT).to_string().into()),
            VddValue::S401 { v, d: _ } => Ok(v.to_string().into()),
            VddValue::S801(v) => Ok(v.to_owned().into()),
            VddValue::S901(v) => Ok(v.0.to_string().into()),
            VddValue::S911(v) => Ok(v.0.to_string().into()),
            _ => Err("转换失败".into()),
        }
    }
}
